<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/6/12 0012
 * Time: 下午 11:46
 */

namespace backend\models;

use backend\models\Manager;
use Yii;
use yii\base\Model;


class LoginForm extends Model
{

    public $username;
    public $password;
    public $veryCode;
    
    private $_user;

    public function rules()
    {
        return [
            [['username','password','veryCode'],'required'],
            ['veryCode','captcha'],
            ['password','validatePassword']
        ];
    }
    
    public function attributeLabels()
    {
       return [
           'username' => Yii::t('app','用户名'),
           'password' => Yii::t('app','密码'),
           'veryCode' => Yii::t('app','验证码'),
       ]; 
    }
    
    public function validatePassword($attribute,$params){
        if(!$this->hasErrors()){
            $user = $this->getUser();
            if(!$user || !$user->validatePassword($this->password)){
                $this->addError('password','用户名或者密码错误');
            }
        }
    }

    public function login(){
        if($this->validate()){
            return Yii::$app->admin->login($this->_user,3600);
        } else {
            return FALSE;
        }
    }
    
    public function getUser(){
        if($this->_user == null){
            $this->_user = Manager::findByUsername($this->username);
        }
        return $this->_user;
    }
}